#include "INIFile.h"
#include "resource.h"

const std::wstring CINIFile::configFileName = TEXT("RegXN.ini");
TCHAR* CINIFile::iniFilePath = 0;

CINIFile::CINIFile(HWND nppHandle)
{
	if (!iniFilePath)
	{
		iniFilePath = new TCHAR[MAX_PATH];
		SendMessage(nppHandle, NPPM_GETPLUGINSCONFIGDIR, MAX_PATH, (LPARAM)iniFilePath);

		if (PathFileExists(iniFilePath) == FALSE)
			CreateDirectory(iniFilePath, NULL);

		PathAppend(iniFilePath, configFileName.c_str());
		CreateFile(iniFilePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);//create new if there is none present
		populateComboBox(nppHandle);
	}
}

CINIFile::~CINIFile()
{
	if (iniFilePath)
		delete iniFilePath;
}



std::wstring CINIFile::GetSection(const size_t index) const
{
	wchar_t groupName[128];
	swprintf(groupName, L"Group_%d", index);
	wchar_t buffer[INI_BUFFER_SIZE];
	size_t bytesReturned = GetPrivateProfileSection(groupName, buffer, INI_BUFFER_SIZE, iniFilePath);
	if (bytesReturned == 0)
		return L"";

	GetPrivateProfileString(groupName,L"name", groupName, buffer, INI_BUFFER_SIZE, iniFilePath);
	return buffer;
}

std::wstring CINIFile::GetFindString(const size_t sectionIndex, const size_t index) const
{
	wchar_t groupName[128];
	swprintf(groupName, L"Group_%d", sectionIndex);
	wchar_t fieldName[128];
	swprintf(fieldName, L"find%d", index);
	return GetSectionField(groupName, fieldName);
	
}

std::wstring CINIFile::GetReplaceString(const size_t sectionIndex, const size_t index) const
{
	wchar_t groupName[128];
	swprintf(groupName, L"Group_%d", sectionIndex);
	wchar_t fieldName[128];
	swprintf(fieldName, L"replace%d", index);
	return GetSectionField(groupName, fieldName);
}

void CINIFile::populateComboBox(HWND windowHandle) const
{
	HWND CB = GetDlgItem(windowHandle, IDC_COMBO_GROUP);
	std::wstring name;
	size_t i = 0;
	while (true)
	{
		name = GetSection(i);
		if (name.compare(L"")==0)
			break;
		SendMessage(CB, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(name.c_str()));
		i++;
	}
}

std::wstring CINIFile::GetSectionField(wchar_t *sectionName, wchar_t *fieldName) const
{
	wchar_t buffer[INI_BUFFER_SIZE];
	GetPrivateProfileString(sectionName, fieldName, L"", buffer, INI_BUFFER_SIZE, iniFilePath);
	return buffer;
}